/** SessionManager */
package postpic.server;

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.logging.Logger;

/**
 * SessionManager manages currently connected sessions in a thread-safe manner.
 */
public class SessionManager {
	
	private static final Logger LOGGER = Logger.getLogger(SessionManager.class.getName());
	
	private static Map<Integer, Integer> sessions = new HashMap<Integer, Integer>();
	private static Map<Integer, Connection> connections = new HashMap<Integer, Connection>();
	
	/**
	 * Adds a session to the session table.
	 * @param userId the id of the session's user
	 * @return Integer the session ID * 
	 * @throws IOException if there are too many sessions */
	public static synchronized Integer addSession(final Integer userId) {
		Integer sessionId = null;
		Random rand = new Random();
		
		while (sessionId == null || sessions.get(sessionId) != null) {
			sessionId = userId * rand.nextInt(100);
		}
		
		LOGGER.info("Session started for userId: " + userId + " sessionId: " + sessionId);
		sessions.put(sessionId, userId);
		return sessionId;
	}
	
	public static synchronized void addConnection(final Integer sessionId, final Connection connection) {
		connections.put(sessionId, connection);
	}
	
	/**
	 * Removes a session from the session table.
	 * @param sessionId the currently open session's id
	 */
	public static synchronized void removeSession(final Integer sessionId) {
		Integer userId = sessions.remove(sessionId);
		if (userId != null) {
			LOGGER.info("Removed session for sessionId: " + sessionId);
			try {
				Connection connection = connections.remove(sessionId);
				connection.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		} else {
			LOGGER.warning("Cannot remove session: Session id " + 
					sessionId + " does not exist!");
		}
	}
	
	/**
	 * Returns the user id associated with the given session id.
	 * @param sessionId the session's id
	 * @return the associated user id */
	public static synchronized Integer getUserId(final Integer sessionId) {
		Integer userId = sessions.get(sessionId);
		
		if (userId == null) {
			LOGGER.warning("Cannot retrieve session: Session id " + 
					sessionId + " does not exist!");
		}
		
		return userId;
	}

}
